﻿/**
 * GoText Palm: A program that allows to send text messages over the internet.
 *  Copyright (C) 2008 Nicola 'Gawaine' Racco
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Threading;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using GoTextPalm.Core;
using GoTextPalm.Core.Data;
using GoTextPalm.Core.Persistence;
using GoTextPalm.Core.Localization;

namespace GoTextPalm.Gui
{
    public delegate void OnNewServiceCreated();

    public partial class NewServiceForm : LocalizedForm
    {
        private Logic logic;

        public NewServiceForm()
        {
            logic = new Logic();
            logic.StatusTextChangedEvent += new Logic.StatusTextChangedHandler(Logic_StatusTextChanged);
            logic.ServiceSavedEvent += new Logic.ServiceSavedHandler(Logic_ServiceSaved);
            logic.ServiceCreatedEvent += new Logic.ServiceCreatedHandler(Logic_ServiceCreated);
            logic.ErrorCausedEvent += new Logic.ErrorCausedHandler(Logic_ErrorCaused);

            InitializeComponent();
            header.Text = "New Service";
            AddMenusToDictionary();
            UpdateResources();
        }

        public NewServiceForm(ServiceCandidate sc) : this()
        {
            txtName.Text = sc.Name;
            txtUrl.Text = sc.URL;
        }

        protected override void AddMenusToDictionary()
        {
            AddMenuToDictionary(mnuSave, "mnuSave");
        }

        private void mnuSave_Click(object sender, EventArgs e)
        {
            String name = txtName.Text.Trim();
            String url = txtUrl.Text.Trim();
            if (name.Length == 0)
                MessageBox.Show(Utility.Tr("NewServiceForm_needname", "Field 'Name' is needed"), header.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
            else if (url.Length == 0)
                MessageBox.Show(Utility.Tr("NewServiceForm_needurl", "Field 'URL' is needed"), header.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
            else
            {
                logic.Name = name;
                logic.URL = url;
                MessageBox.Show(Utility.Tr("NewServiceForm_nowdl", "gTP will now doenload service information"), header.Text, MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
                lblName.Enabled = lblUrl.Enabled = txtName.Enabled = txtUrl.Enabled = mnuSave.Enabled = false;
                new Thread(new ThreadStart(logic.CreateService)).Start();
            }
        }

        private void NewServiceForm_Load(object sender, EventArgs e)
        {
            if (customInputPanel.SipSupported)
            {
                customInputPanel.Screen = screen;
                customInputPanel.Refresh();
            }
        }


        public void Logic_StatusTextChanged(String text)
        {
            if (InvokeRequired)
            {
                Logic.StatusTextChangedHandler func = Logic_StatusTextChanged;
                Invoke(func, text);
                return;
            }
            if (!stsBar.Visible)
                stsBar.Visible = stsBar.ProgressStarted = true;
            stsBar.Text = text;
        }

        public void Logic_ServiceCreated(Service s)
        {
            if (InvokeRequired)
            {
                Logic.ServiceCreatedHandler func = Logic_ServiceCreated;
                Invoke(func, s);
                return;
            }
            stsBar.Visible = stsBar.ProgressStarted = false;
            lblName.Enabled = lblUrl.Enabled = txtName.Enabled = txtUrl.Enabled = mnuSave.Enabled = true;

            DialogResult toContinue = MessageBox.Show(String.Format(
                Utility.Tr("NewServiceForm_savesrv", 
                "{0}\rDo you want to save the service ?"), 
                s.Welcome.IsNull ? "" : s.Welcome.Value),
                header.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question,
                MessageBoxDefaultButton.Button1);
            if (toContinue == DialogResult.Yes)
                new Thread(new ThreadStart(logic.PersistService)).Start();
        }

        public void Logic_ErrorCaused(String text)
        {
            if (InvokeRequired)
            {
                Logic.ErrorCausedHandler func = Logic_ErrorCaused;
                Invoke(func, text);
                return;
            }
            stsBar.Visible = stsBar.ProgressStarted = false;
            lblName.Enabled = lblUrl.Enabled = txtName.Enabled = txtUrl.Enabled = mnuSave.Enabled = true;

            MessageBox.Show(text, header.Text, MessageBoxButtons.OK, 
                MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
        }

        public void Logic_ServiceSaved(Service s)
        {
            if (InvokeRequired)
            {
                Logic.ServiceSavedHandler func = Logic_ServiceSaved;
                Invoke(func, s);
                return;
            }
            stsBar.Visible = stsBar.ProgressStarted = false;
            lblName.Enabled = lblUrl.Enabled = txtName.Enabled = txtUrl.Enabled = mnuSave.Enabled = true;

            MessageBox.Show(Utility.Tr("NewServiceForm_newsrv2", "Service Created"), 
                header.Text, MessageBoxButtons.OK, MessageBoxIcon.None, 
                MessageBoxDefaultButton.Button1);
            Close();
        }


        private void NewServiceForm_Closing(object sender, CancelEventArgs e)
        {
            DialogResult = logic.Service != null ? DialogResult.OK : DialogResult.Cancel;
        }


        private class Logic
        {
            public delegate void StatusTextChangedHandler(String text);
            public event StatusTextChangedHandler StatusTextChangedEvent;

            public delegate void ServiceCreatedHandler(Service s);
            public event ServiceCreatedHandler ServiceCreatedEvent;

            public delegate void ServiceSavedHandler(Service s);
            public event ServiceSavedHandler ServiceSavedEvent;

            public delegate void ErrorCausedHandler(String text);
            public event ErrorCausedHandler ErrorCausedEvent;

            public Service Service;

            public void PersistService()
            {
                try
                {
                    ServiceLogic.PersistService(ref Service);
                    FireServiceSaved(Service);
                }
                catch (Exception ex)
                {
                    FireErrorCaused(String.Format(Utility.Tr("NewServiceForm_cantsave",
                        "Cannot save the Service: {0}"), ex.Message));
                }
            }

            public String Name, URL;

            public void CreateService()
            {
                FireStatusTextChanged(Utility.Tr("NewServiceForm_newsrv1", 
                    "Service Creation ..."));
                try
                {
                    Service = ServiceLogic.CreateService(Name, URL);
                    FireServiceCreated(Service);
                }
                catch (Exception ex)
                {
                    FireErrorCaused(String.Format(Utility.Tr("NewServiceForm_fetchex", 
                        "Fetching data operation failed: {0}"), ex.Message));
                }
            }

            private void FireServiceSaved(Service s)
            {
                if (ServiceCreatedEvent != null)
                    ServiceSavedEvent(s);
            }

            private void FireErrorCaused(String text)
            {
                if (ErrorCausedEvent != null)
                    ErrorCausedEvent(text);
            }

            private void FireStatusTextChanged(String text)
            {
                if (StatusTextChangedEvent != null)
                    StatusTextChangedEvent(text);
            }

            private void FireServiceCreated(Service s)
            {
                if (ServiceCreatedEvent != null)
                    ServiceCreatedEvent(s);
            }
        }
    }
}